package com.yaowk.sfp.utils.init.sql.resource;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yaowk.sfp.common.base.utils.HttpUtils;
import lombok.Data;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Set;

@Data
public class ResourceSql {

    private Long menuId;
    private Long idBegin;
    private String projectName = "";
    private String basePath = "/src/test/java/";
    private String fileName = "resource.sql";
    private String sqlTemplate = "insert into sys_resource (id, method, resource, name) values (%s, '%s', '%s', '%s');%n";
    private String sqlTemplate2 = "insert into sys_menu_resource (menu_id,resource_id) values (%s, %s);%n";

    public void createSql(String url) throws IOException {
        String path = new File(ResourceSql.class.getResource("/").getFile()).getParentFile().getParentFile().getCanonicalPath() + basePath + fileName;

        FileWriter fw = new FileWriter(path);

        StringBuilder stringBuilder = new StringBuilder();
        String receive = HttpUtils.get(url);
        System.out.println(receive);
        JSONObject jsonObject = JSON.parseObject(receive);
        JSONObject paths = jsonObject.getJSONObject("paths");
        Set<String> keys = paths.keySet();
        keys.remove("/error");
        for (String key : keys) {
            JSONObject jsonObject1 = paths.getJSONObject(key);
            Set<String> methods = jsonObject1.keySet();
            for (String method : methods) {
                String summary = jsonObject1.getJSONObject(method).getString("summary");
                String resource = key.replaceAll("\\{[A-Za-z]+\\}", "*");
                resource = projectName + resource;
                stringBuilder.append(String.format(sqlTemplate, idBegin, method.toUpperCase(), resource, summary));
                stringBuilder.append(String.format(sqlTemplate2, menuId, idBegin));
                idBegin++;
            }
        }

        fw.write(stringBuilder.toString());

        fw.flush();
        fw.close();
    }
}
